<template>
  <div>
    <folder-tree
      ref="folderTree"
      :name="name"
      :menu-folder-list="menuFolderList"
      :menu-file-list="menuFileList"
      :click-functions="clickFunctions"
      @dbl-click-node="changeNode"
      @create-file="createFile"
      @click-node="clickNode"
      @rename="rename"
      @delete="askDelete"
      @selectedProjectId="selectedProjectId"
    />
    <file-upload-dialog ref="fileUploadDialog" />
    <DependencyDialog :show-dialog="showDependencyDialog" :project-id="projectId" @closeDialog="closeDialog" />
  </div>
</template>

<script>
import FolderTree from '@/components/FolderTree';
import DependencyDialog from '@/views/matlab/component/DependencyDialog.vue';
import FileUploadDialog from '@/views/matlab/plugins/dialog/FileUploadDialog.vue';

export default {
  name: 'MatlabFolderTree',
  components: {
    DependencyDialog,
    FolderTree,
    FileUploadDialog
  },
  data() {
    return {
      name: 'matlab',
      showDependencyDialog: false,
      projectId: '',
      menuFolderList: [
        { style: 'item', type: 'open', title: '打开' },
        { style: 'item', type: 'dependency', title: '依赖管理' },
        { style: 'divider' },
        { style: 'item', type: 'rename', title: '重命名' },
        { style: 'item', type: 'remove', title: '删除' },
        // { style: 'item', type: 'zip', title: '压缩成zip' },
        {
          style: 'submenu',
          title: '新建',
          children: [
            {
              style: 'item',
              type: 'buildFolder',
              title: '文件夹',
              icon: 'icon-build-fold'
            },
            {
              style: 'item',
              type: 'buildFile',
              title: '脚本',
              icon: 'icon-build-script'
            }
            // {
            //   style: 'item',
            //   type: 'buildFunction',
            //   title: '函数',
            //   icon: 'icon-build-function'
            // },
            // {
            //   style: 'item',
            //   type: 'buildExample',
            //   title: '图窗',
            //   icon: 'icon-build-example'
            // },
            // {
            //   style: 'item',
            //   type: 'buildClass',
            //   title: '类',
            //   icon: 'icon-build-class'
            // },
            // {
            //   style: 'item',
            //   type: 'buildZip',
            //   title: 'zip',
            //   icon: 'icon-build-zip'
            // }
          ]
        },
        { style: 'item', type: 'upload', title: '上传' }
        // { style: 'divider' },
        // { style: 'item', type: 'cut', title: '剪切', icon: 'icon-cut' },
        // { style: 'item', type: 'copy', title: '复制', icon: 'icon-copy' },
        // { style: 'item', type: 'paste', title: '粘贴', icon: 'icon-paste' }
      ],
      menuFileList: [
        { style: 'item', type: 'run', title: '运行' },
        { style: 'item', type: 'open', title: '打开' },
        { style: 'divider' },
        { style: 'item', type: 'rename', title: '重命名' },
        { style: 'item', type: 'download', title: '下载' },
        { style: 'item', type: 'remove', title: '删除' }
        // { style: 'item', type: 'zip', title: '压缩成zip' },
        // { style: 'divider' },
        // { style: 'item', type: 'cut', title: '剪切', icon: 'icon-cut' },
        // { style: 'item', type: 'copy', title: '复制', icon: 'icon-copy' },
        // { style: 'item', type: 'paste', title: '粘贴', icon: 'icon-paste' }
      ]
    };
  },
  methods: {
    changeNode(node) {
      const data = node.data;
      if (data.isFile) {
        const label = data.label;
        const supportedFileTypes = ['json', 'py', 'txt', 'yaml'];
        const suffix = label.slice(label.lastIndexOf('.') + 1);
        if (!supportedFileTypes.includes(suffix)) {
          this.$message('暂不支持预览该文件类型');
          return;
        }
        this.$store.dispatch('matlab/getFile', data)
          .then(() => {
            this.$message({
              message: `打开文件${node.label}`,
              offset: 40,
              type: 'success'
            });
          })
          .catch((err) => {
            this.$message.error(err);
          });
        // 添加打开文件提示，文件夹不提示
        return;
      }
      const bread = [data];
      while (node.parent && node.parent?.id !== 0) {
        const nodeParent = node.parent;
        bread.unshift(nodeParent.data);
        node = nodeParent;
      }
      this.$store.commit('matlab/resetBreadcrumb', {
        type: 'push',
        item: data,
        bread
      });
    },
    // 浏览文件夹跳转对应节点
    setBread(id, node) {
      const state = this.$store.state.matlab.breadcrumb;
      if (id === 0) {
        if (state.length > 0) {
          this.$store.commit('matlab/resetTreeData');
        }
        return;
      }
      if (state.length > 0 && id === state.at(-1).id) {
        return;
      }
      const data = node.data;
      const bread = [data];
      while (node.parent && node.parent?.level !== 0 && node.parent?.id !== 0) {
        const nodeParent = node.parent;
        bread.unshift(nodeParent.data);
        node = nodeParent;
      }
      this.$store.commit('matlab/resetBreadcrumb', {
        type: 'change',
        index: 0,
        item: data,
        bread
      });
    },
    clickFunctions(type, options) {
      const { node, data } = options;
      let m;
      switch (type) {
        case 'open':
          this.changeNode(node, data);
          break;
        case 'buildFolder':
        case 'buildFile':
          // 先展开树节点，再显示编辑框
          this.$refs.folderTree.expandNode(data);
          this.$store.commit('matlab/append', {
            nodeType: 'child',
            type,
            data
          });
          break;
        case 'remove':
          this.askDelete(options, data);
          break;
        case 'upload':
          this.openUpload(data);
          break;
        case 'rename':
          this.rename(data);
          break;
        case 'run':
          m = this.$message({
            message: '正在运行中...',
            offset: 40,
            duration: 0
          });
          this.$store.dispatch('matlab/run', data).then(() => {
            this.$message({
              message: '代码文件运行完成',
              type: 'success',
              offset: 40
            });
          }).catch((err) => {
            this.$message({
              message: '代码文件运行失败',
              type: 'error',
              offset: 40
            });
            console.error(err);
          }).finally(() => {
            m.close();
          });
          break;
        case 'download':
          this.$store.dispatch('matlab/downloadFile');
          break;
        case 'dependency':
          this.showDependencyDialog = true;
          break;
        default:
          this.$message.info('二期');
      }
    },
    closeDialog() {
      this.showDependencyDialog = false;
    },
    selectedProjectId(data) {
      this.projectId = data;
    },
    clickNode(data) {
      if (data.isFile) {
        this.$store.commit('matlab/setUploadNode', null);
        this.$store.commit('matlab/setDownloadFile', data);
      } else {
        this.$store.commit('matlab/setUploadNode', data);
        this.$store.commit('matlab/setDownloadFile', null);
      }
    },
    askDelete(options, data) {
      const str = data.isFile ? '文件' : '文件夹';
      this.$confirm(`此操作将永久删除该${str}(${data.label}), 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('matlab/remove', options);
        this.$store.dispatch('matlab/remove', data);
        this.$store.state.matlab.downloadFile = '';
      });
    },
    async createFile(node, filename) {
      // 这个地方加了一个对项目的创建中文件名称的检查，不可以使用单引号
      const { data } = node;
      if (data.isFile === false && !data.path && /'/g.test(filename)) {
        filename = 'New Project';
        this.$message({
          message: "项目命名不可以带有单引号：'",
          type: 'warning'
        });
      }
      data.label = filename.trim();
      const flag = data.isFile && data.isFirstBuild;
      data.isFirstBuild = false;
      // 当修改了项目的文件夹对应label时，对项目名称进行修改
      if (data.isFile === false && !data.path) {
        data.projectName = data.label;
      }
      // 这个地方对更改过名称的文件夹下的文件路径进行更新，防止使用zip上传后出现文件夹的纰漏
      if (data.isFile === false) {
        await this.$store.dispatch(`matlab/updateChildPath`, data);
      } else if (data.isFile === true) {
        await this.$store.dispatch(`matlab/handleEditorFileName`, data);
      }
      this.$store.dispatch(`matlab/append`, data);
      if (flag) {
        this.$store.dispatch(`matlab/buildFiles`, data);
      }
    },
    openUpload(data) {
      this.$store.commit('matlab/setUploadNode', data);
      this.$store.commit('matlab/setDownloadFile', null);
      this.$refs.fileUploadDialog.show();
    },
    rename(data) {
      this.$store.commit('matlab/editName', data);
    }
  }
};
</script>
